<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
namespace core;
defined('BY_JYA') or exit('error');
class files{
	private $setting;
	public function __construct(){
		$this->setting=IS_UNI_ATTACHMENT==1?uni_setting('upload'):core_setting('upload');
	}
	//压缩
	public function zip($dir, $to,$ignore=array(),$types=array(),$filename='') {
		if(!$dir){
			exi('压缩失败，缺少源文件！','error');
		}
		if($to=='data' || $to=='source'){
			$temp=ROOT_AT.random(15).'.z';
		}else{
			$temp=$to;
		}
		//if(function_exists('exec')){
		//	exec('cd '.$dir.' && zip -q -r '.$temp.' ./*');
		//}else{
			$tree=$this->file_tree($dir,$ignore,$types);
			if(!class_exists('\ZipArchive')){
				return error('检测不到类：ZipArchive');
			}
			$zip = new \ZipArchive();
			$zip->open($temp, \ZipArchive::CREATE);
			foreach($tree as $v) {
				$fname = $dir . $v;
				$zip->addFile($fname,$v);
			}
			$zip->close();
		//}
		if(!is_file($temp)){
			exi('文件压缩失败！','error');
		}
		if($to=='data'){
			$return=file_get_contents($temp);
		}elseif($to=='source'){
			$return= $this->source_save($temp,'data','zip','',$filename);
		}else{
			return true;
		}
		@unlink($temp);
		return $return;
	}
	//解压
	public function unzip($file, $to) {
		if(!class_exists('\ZipArchive')){
			return error('检测不到类：ZipArchive');
		}
		$zip = new \ZipArchive();
		$zip->open($file);
		$zip->extractTo($to);
		$zip->close();
		return true;
	}
	//创建目录树
	public function make_tree($path,&$trees,$ignores=array(),$exts=array(),$repath='',$num=0){
		$count=count($trees);
		if(!$repath){
			$repath=$path;
		}
		$tree=scandir($path);
		foreach($tree as $row){
			if($row!='.' && $row!='..'){
				//判断是否忽略
				$file_dir=str_replace($repath,'',$path.'/'.$row);
				if($ignores && in_array($file_dir,$ignores)){
					continue;
				}
				$temp=array('name'=>$row,'num'=>$num);
				if($count){
					$temp['father']=$count-1;
				}
				if(is_dir($path.'/'.$row)){
					$temp['type']=1;
					$temp['id']=$file_dir;
					$trees[]=$temp;
					$this->make_tree($path.'/'.$row,$trees,$ignores,$exts,$repath,$num+1);
				}else{
					$ext=$this->get_ext($row);
					if(!$exts || in_array($ext,$exts)){
						$temp['type']=2;
						$temp['id']=$file_dir;
						$trees[]=$temp;
					}
					
				}
			}
		}
		$temp=array('name'=>'添加','num'=>$num,'type'=>3,'dir'=>str_replace($repath,'',$path));
		if($count){
			$temp['father']=$count-1;
		}
		$trees[]=$temp;
	}
	public function get_ext($file){
		if(!$file){
			return false;
		}
		$ext=strrchr($file,'.');
		if(!$ext){
			return false;
		}
		return substr($ext,1);
	}
	//获取指定目录文件列表
	public function file_tree($path,$ignore=array(),$types=array(),$rpath='') {
		if(!is_array($ignore)){
			$ignore=array($ignore);
		}
		if(!is_array($types)){
			$types=array($types);
		}
		$files = array();
		if(!$rpath){
			$rpath=$path;
		}
		$ds = glob($path . '/*');
		if (is_array($ds)) {
			foreach ($ds as $entry) {
				$entry=str_replace('\\', '/', $entry);
				$entry=str_replace($rpath, '', $entry);
				if(in_array($entry,$ignore)){
					continue;
				}
				if (is_file($rpath.$entry)) {
					
					if(empty($types)){
						$files[] = $entry;
					}else{
						$type=strrchr($entry,'.');
						if(in_array($type,$types)){
							$files[] = $entry;
						}
					}
				}
				if (is_dir($rpath.$entry)) {
					$rs = $this->file_tree($rpath.$entry,$ignore,$types,$rpath);
					foreach ($rs as $f) {
						$files[] = $f;
					}
				}
			}
		}
		return $files;
	}
	//递归创建目录
	public function mkdirs($path) {
		
		if (!is_dir($path)) {
			$this->mkdirs(dirname($path));
			mkdir($path);
		}
		return is_dir($path);
	}
	//复制文件夹
	public function file_copy($src, $des) {
		$dir = opendir($src);
		@mkdir($des);
		while (false !== ($file = readdir($dir))) {
			if (($file != '.') && ($file != '..')) {
				if (is_dir($src . '/' . $file)) {
					$this->file_copy($src . '/' . $file, $des . '/' . $file);
				} else{
					copy($src . '/' . $file, $des . '/' . $file);
				}
			}
		}
		closedir($dir);
	}
	//递归删除指定目录下的所有子文件夹和文件，第二项为真保留指定目录，否则连同指定目录一起删除
	public function rmdirs($path, $hold = false) {
		if (!is_dir($path)) {
			return false;
		}
		$files = glob($path . '/*');
		if ($files) {
			foreach ($files as $file) {
				is_dir($file) ? $this->rmdirs($file) : @unlink($file);
			}
		}
		return $hold ? true : @rmdir($path);
	}
	//生成附件文件路径
	public function get_source_name($type,$ext='data'){
		$ext=$ext?:'data';
		$this->mkdirs(ROOT_AT.'oss/'.$_SESSION['uniacid'].'/'.$type.'s/'.date('20y/m'));
		do {
			$filename = 'oss/'.$_SESSION['uniacid'].'/'.$type.'s/'.date('20y/m').'/'.random(10) . '.' . $ext;
		} while (file_exists(ROOT_AT .$filename));
		return $filename;
	}
	//检查附件是否存在
	public function source_check($file){
		$id=pdo_getcolumn('core_attachment',array('attachment'=>$file,'uniacid'=>$_SESSION['uniacid']),'id');
		if($id){
			if (is_file(ROOT_AT.$file)) {
					return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	//读取附件内容
	public function source_read($file,$isroot=false){
		global $_AR;
		if($isroot && IS_UNI_ATTACHMENT==1){
			if (ATTACHMENT_ROOTTYPE == '0') {
				$file=ROOT_AT.$file;
				if(!is_file($file)){
					return false;
				}
			}elseif(ATTACHMENT_ROOTTYPE == '5'){
				$data=$this->source_diy_request('read',array('file'=>$file),$isroot);
				return $data;
			}else{
				$file=ATTACHMENT_ROOTURL.$file;
			}
		}else{
			if (ATTACHMENT_TYPE == '0') {
				$file=ROOT_AT.$file;
				if(!is_file($file)){
					return false;
				}
			}elseif(ATTACHMENT_TYPE == '5'){
				$data=$this->source_diy_request('read',array('file'=>$file));
				return $data;
			}else{
				$file=ATTACHMENT_URL.$file;
			}
		}
		return @file_get_contents($file);
	}
	public function url_source_save($url,$type='image',$title=''){
		$data=file_get_contents($url);
		if(!$data){
			return error('url资源无效');
		}
		$ext=substr(strrchr($url,'.'),1);
		return $this->source_save($data,$type,$ext,$title);
	}
	//将附件保存到本地，并返回本地路径
	public function local($file){
		$local_file=ROOT_AT.$file;
		if(ATTACHMENT_TYPE){
			$file_data=$this->source_read($file);
			$this->mkdirs(dirname($local_file));
			file_put_contents($local_file,$file_data);
		}
		return $local_file;
	}
	public function wechat_image_url($image){
		$attachment=pdo_get('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','attachment'=>$image),array('id','wx_url'));
		if(!$attachment){
			return '';
		}else{
			if(!$attachment['wx_url']){
				$api_url='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={access_token}';
				$local=$this->local($image);
				$params=array(
					'media'=>'@'.$local,
				);
				$res=cfc('account')->request($api_url,$params);
				if($res['url']){
					$attachment['wx_url']=$res['url'];
					pdo_update('core_attachment',array('wx_url'=>$res['url']),array('id'=>$attachment['id']));
				}
			}
			return $attachment['wx_url'];
		}
	}
	//保存附件
	public function source_save($from,$type='data',$ext='data',$title='未设置标题',$filename='',$group_id=0,$wx_url='',$islocal=false){
		//附件保存功能。$from支持文件路径和文件内容两种形式。$filename如果为空，系统将自动创建附件路径，保存成后，函数返回附件相对路径。
		global $_AR;
		if(!$type){
			$type='data';
		}
		if(!$ext){
			$ext='data';
		}
		$check=@is_file($from);
		if(!$check){
			$check=@is_file(ROOT_AT.$from);
			if($check){
				$from=ROOT_AT.$from;
			}
		}
		if(!$check){
			$temp=ROOT_AT.random(30).'.temp';
			//写入文件
			file_put_contents($temp,$from);
			$from=$temp;
		}
		$md5=md5_file($from);
		//检查是否有相同文件
		if($type=='image' || $type=='video' || $type=='audio'){
			$check=pdo_getcolumn('core_attachment',array('md5'=>$md5,'type'=>$type,'mid'=>$_SESSION['this']=='custom'?$_SESSION['uid']:0,'uniacid'=>$_SESSION['uniacid']),'attachment');
			if($wx_url && !$check){
				$check=pdo_getcolumn('core_attachment',array('wx_url'=>$wx_url,'type'=>$type,'mid'=>$_SESSION['this']=='custom'?$_SESSION['uid']:0,'uniacid'=>$_SESSION['uniacid']),'attachment');
			}
			if($check){
				if (is_file(ROOT_AT.$check)) {
					return $check;
				}
			}
		}
		$size=filesize($from);
		//检查站点附件容量是否达到上限
		if($_SESSION['uniacid']){
			$resource_limit=model('core/web')->get_resource_limit($_SESSION['uniacid']);
			$total_size=pdo_fetch('select sum(`size`) from `'.TABLE_PRE.'core_attachment` where `uniacid`='.$_SESSION['uniacid']);
			$total_size=$total_size['sum(`size`)'];
			if($resource_limit && $resource_limit<$total_size){
				exi('您的站点附件已超出套餐容量限制，无法再上传附件资源！请先整理站点附件或者升级套餐！','error');
			}
		}
		//如果启用图片压缩。则检查图片是否太大，如果太大，则对图片进行压缩
		if(!$filename){
			$is_new=true;
			$filename=$this->get_source_name($type,$ext);
		}else{
			$key=intval($filename);
			if($key){
				$filename=pdo_getcolumn('core_attachment',array('id'=>$key),'attachment');
			}
		}
		
		if($this->setting['thumb'] && $type=='image'){
			$thumb=true;
			$from=$this->file_image_thumb($from);
		}
		if (ATTACHMENT_TYPE == '0' || $islocal) {
			copy($from,ROOT_AT.$filename);
		}elseif (ATTACHMENT_TYPE == '1'){
			require_once(ROOT_D . '/core/library/ftp/ftp.php');
			if(!$this->setting['ftp_ip'] || !$this->setting['ftp_user'] || !$this->setting['ftp_psw']|| !$this->setting['ftp_dk']){
				exi('FTP服务器参数设置异常，无法上传！','error');
			}
			$ftp_config = array(
				'hostname' => $this->setting['ftp_ip'],
				'username' => $this->setting['ftp_user'],
				'password' => $this->setting['ftp_psw'],
				'port' => $this->setting['ftp_dk'],
				'ssl' => $this->setting['ftp_ssl'],
				'passive' => $this->setting['ftp_pasv'],
				'timeout' => '100',
				'rootdir' => $this->setting['ftp_dir'],
			);
			$ftp = new Ftp($ftp_config);
			if (true === $ftp->connect()) {
				$response = $ftp->upload($from, $filename);
				if (empty($response)) {
					exi('ftp远程附件上传失败！请检查附件配置！');
				}
			}
		}elseif (ATTACHMENT_TYPE == '2') {
		    $this->source_save_oss($from,$filename);
		}elseif (ATTACHMENT_TYPE == '3') {
		    if(!$is_new){
				//尝试删除已存在的文件
				 require_once(ROOT_D . '/core/library/qiniu/autoload.php');
                $auth = qndel($this->setting['qiniu_accesskey'], $this->setting['qiniu_secretkey']);
                $config = new \Qiniu\Config();
                $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
                $err = $bucketManager->delete($this->setting['qiniu_bucket'], $filename);
			}
			$this->source_save_qiniu($from,$filename);
		} elseif (ATTACHMENT_TYPE == '4') {	
			$this->source_save_cos($from,$filename);
		}elseif (ATTACHMENT_TYPE == '5') {	
			//自定义资源站
			$this->source_save_diy($from,$filename);
		}
		if($temp){
			@unlink($temp);
		}
		if($thumb){
			@unlink($from);
		}
		if($is_new){
			$insert=array(
				'uniacid' => $_SESSION['uniacid'],
				'mid' => $_SESSION['this']=='custom'?$_SESSION['uid']:0,
				'group_id'=>$group_id,
				'title' => $title,
				'attachment' => $filename,
				'type' => $type,
				'createtime' => TIMESTAMP,
				'md5'=>$md5,
				'size'=>$size,
				'wx_url'=>$wx_url
			);
			pdo_insert('core_attachment',$insert);
		}
		return $filename;
	}
	//保存七牛云附件
	public function source_save_qiniu($from,$filename){
		if(!$this->setting['qiniu_accesskey'] || !$this->setting['qiniu_secretkey'] || !$this->setting['qiniu_bucket']){
				exi('七牛云参数设置异常，无法上传！','error');
		}
		require_once(ROOT_D . '/core/library/qiniu/autoload.php');
		$accessKey = $this->setting['qiniu_accesskey'];
		$secretKey = $this->setting['qiniu_secretkey'];
		$bucket = $this->setting['qiniu_bucket'];
		$auth = auth($accessKey, $secretKey);
		// 生成上传 Token
		$token = $auth->uploadToken($bucket);
		// 要上传文件的本地路径
		$filePath = $from;
		// 上传到七牛后保存的文件名
		$key = $filename;
		// 初始化 UploadManager 对象并进行文件的上传。
		$uploadMgr = uploadMgr();
		// 调用 UploadManager 的 putFile 方法进行文件的上传。
		list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
		if ($err !== null) {
		   exi('上传失败：','error');
		}
		return true;
	}
	//保存阿里云oss附件
	public function source_save_oss($from,$filename){
		if(!$this->setting['ali_accessid'] || !$this->setting['ali_accesskey'] || !$this->setting['ali_endpoint'] || !$this->setting['ali_bucket']){
				exi('阿里云oss参数设置异常，无法上传！','error');
		}
	    require_once(ROOT_D.'/core/library/alioss/autoload.php');	    
		$ossClient = make_oss_Client($this->setting['ali_accessid'], $this->setting['ali_accesskey'], $this->setting['ali_endpoint']);
		$bucketlistinfo =$ossClient->doesBucketExist($this->setting['ali_bucket']);
		if($bucketlistinfo!==true){
				 exi('空间不存在','error');   
		}
		$ossClient->uploadFile($this->setting['ali_bucket'], $filename,$from);
	}
	//保存腾讯云附件
	public function source_save_cos($from,$filename){
			if(!$this->setting['tx_appid'] || !$this->setting['tx_secretid'] || !$this->setting['tx_secretkey']){
				exi('腾讯云oss参数设置异常，无法上传！','error');
			}
			require_once(ROOT_D.'/core/library/cosv5/index.php');
			$config = array(
                'app_id' => $this->setting['tx_appid'],
                'secret_id' => $this->setting['tx_secretid'],
                'secret_key' => $this->setting['tx_secretkey'],
                'region' => $this->setting['tx_region'],
                'timeout' => 60
            );
            try {
				$bucket = $this->setting['tx_bucket'] . '-' . $config['app_id'];
				$cosClient = new \Qcloud\Cos\Client(
					array(
						'region' => $config['region'],
						'credentials'=> array(
							'secretId'  => $config['secret_id'],
							'secretKey' => $config['secret_key']
						)
					)
				);
				$cosClient->Upload($bucket, $filename, fopen($from, 'rb'));
			} catch (\Exception $e) {
				$errormsg=$e->getMessage();
				exi($errormsg,'error');
			}		
	}
	//保存附件至自定义资源站
	public function source_save_diy($from,$filename){
		$temp=random(30).'zip';
		copy($from,ROOT_AT.$temp);
		$source=SITEROOT.RESOURCE.'/'.$temp;
		$post=array(
			'from'=>$source,
			'to'=>$filename,
		);
		$this->source_diy_request('add',$post);
		@unlink(ROOT_AT.$temp);
		return true;
	}
	private function source_diy_request($do,$par,$isroot=false){
		if($isroot && IS_UNI_ATTACHMENT==1){
			$this->setting=core_setting('upload');
			if($this->setting['jya_request']){
				$post_url=$this->setting['jya_request'].'/resource.php';
			}elseif($this->setting['jya_url']){
				$post_url=$this->setting['jya_url'].'/resource.php';
			}else{
				exi('系统附件设置未设置资源请求地址！','error');
			}
		}else{
			if($this->setting['jya_request']){
				$post_url=$this->setting['jya_request'].'/resource.php';
			}elseif($this->setting['jya_url']){
				$post_url=$this->setting['jya_url'].'/resource.php';
			}else{
				exi('系统附件设置未设置资源请求地址！','error');
			}
		}
		$post=array(
			'do'=>$do,
			'data'=>$par,
			'timestamp'=>TIMESTAMP,
		);
		$post=cfc('tools')->base64_encode(ijson_encode($post));
		if($isroot || IS_UNI_ATTACHMENT==0){
			$source_key=core_setting('source_key');
		}else{
			$source_key=unit_setting('source_key');
		}
		$source_key=$source_key['source_key'];
		if(!$source_key){
			exi('附件上传失败1！','error');
		}
		$sign=md5($post.$source_key);
		$post=$sign.$post;
		$params=array(
			'data'=>$post,
		);
		$res=cfc('http')->ihttp_request($post_url,$params);
		if(!$res['content']){
			exi('访问附件资源站失败！没有收到数据：'.$res['code'],'error');
		}
		$res=$res['content'];
		$res=@unserialize(base64_decode($res));
		if($res['type']=='success'){
			return $res['message'];
		}else{
			exi('访问附件资源站失败！错误详情：'.$res['message'],'error');
		}
	}
	//删除附件
	public function source_del($id){
	    	global $_AR;
		if(intval($id)){
			$isid=true;
			$filename=pdo_getcolumn('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'id'=>$id),'attachment');
		}else{
			$filename=$id;
		}
		if(!$filename){
			return false;
		}
		if(ATTACHMENT_TYPE == '0'){
    		if(is_file(ROOT_AT.$filename)){
    			@unlink(ROOT_AT.$filename);
    		}
		}else{
		       if(ATTACHMENT_TYPE == '1'){
		            
		        }elseif(ATTACHMENT_TYPE == '2'){
					//阿里oss删除附件
					require_once(ROOT_D.'/core/library/alioss/autoload.php');
					$url=$this->setting['ali_endpoint'];
					$ossClient = make_oss_Client($this->setting['ali_accessid'], $this->setting['ali_accesskey'], $url);
					try {
						$ossClient->deleteObject($this->setting['ali_bucket'],$filename);
					} catch (OssException $e) {
						printf($e->getMessage() . "\n");
						return;
					}
				}elseif(ATTACHMENT_TYPE == '3'){
					//七牛删除附件
					require_once(ROOT_D . '/core/library/qiniu/autoload.php');
					$auth = qndel($this->setting['qiniu_accesskey'], $this->setting['qiniu_secretkey']);
					$config = new \Qiniu\Config();
					$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
					$err = $bucketManager->delete($this->setting['qiniu_bucket'], $filename);
					if ($err) {
						print_r($err);
					}
		        }elseif(ATTACHMENT_TYPE == '4'){
					//腾讯cos 删除附件
					require(ROOT_D.'/core/library/cos/sample.php');
					$config = array(
						'app_id' => $this->setting['tx_appid'],
						'secret_id' => $this->setting['tx_secretid'],
						'secret_key' => $this->setting['tx_secretkey'],
						'region' => $this->setting['region'],   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
						'timeout' => 60
					);
				
					$cosApi = make_cos_api($config);
					$ret = $cosApi->delFile($this->setting['tx_bucket'], $filename);
					if($ret['code']!=0){
						//exi('删除失败：'.$ret['message'],'error');
					}
		        }elseif(ATTACHMENT_TYPE == 5){
					$this->source_diy_request('del',array('file'=>$filename));
				}
		}
		if($isid){
			pdo_delete('core_attachment',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}else{
			pdo_delete('core_attachment',array('attachment'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}
		
		return true;
	
	}
	//图片缩略
	public function file_image_thumb($srcfile, $desfile = '', $width = 0) {
		global $_AR;
		if (!file_exists($srcfile)) {
			return error( '原图像不存在');
		}
		if (!$width){
			$width = $this->setting['width'];
		}
		$width=intval($width);
		if(!$width){
			$width=800;
		}
		if (empty($desfile)) {
			$ext = pathinfo($srcfile, PATHINFO_EXTENSION);
			$desfile=$this->get_source_name('image',$ext);
			$desfile=ROOT_AT.$desfile;
		}
		$org_info = @getimagesize($srcfile);
		if (!$org_info){
			exi( '获取原始图像信息失败','error');
		}
		if ($width == 0 || $width > $org_info[0]) {
			copy($srcfile, $desfile);
			return $desfile;
		}
		if ($org_info[2] == 2) {
			if (function_exists("imagecreatefromjpeg")) {
				$img_org = imagecreatefromjpeg($srcfile);
			}
		}elseif ($org_info[2] == 3){
			if (function_exists("imagecreatefrompng")) {
				$img_org = imagecreatefrompng($srcfile);
				imagesavealpha($img_org, true);
			}
		}else{
			copy($srcfile, $desfile);
			return $desfile;
		}
		$scale_org = $org_info[0] / $org_info[1];
		$height = $width/$scale_org;
		if (function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$img_dst = imagecreatetruecolor($width, $height)) {
			imagealphablending($img_dst, false);
			imagesavealpha($img_dst, true);
			imagecopyresampled($img_dst, $img_org, 0, 0, 0, 0, $width, $height, $org_info[0], $org_info[1]);
		}else{
			exi( 'PHP环境不支持图片处理','error');
		}
		if ($org_info[2] == 2) {
			if (function_exists('imagejpeg')) {
				imagejpeg($img_dst, $desfile);
			}
		} else {
			if (function_exists('imagepng')) {
				imagepng($img_dst, $desfile);
			}
		}
		imagedestroy($img_dst);
		imagedestroy($img_org);
		return $desfile;
	}
	//图片裁剪
	public function file_image_crop($src, $desfile, $width = 400, $height = 300, $position = 1) {
		if (!file_exists($src)) {
			return error( '原图像不存在');
		}
		if (intval($width) <= 0 || intval($height) <= 0) {
			return error( '裁剪尺寸无效');
		}
		if (intval($position) > 9 || intval($position) < 1) {
			return error( '裁剪位置无效');
		}

		$des = dirname($desfile);
			if (!file_exists($des)) {
			if (!$this->mkdirs($des)) {
				return error( '创建目录失败');
			}
		} elseif (!is_writable($des)) {
			return error( '目录无法写入');
		}
			$org_info = @getimagesize($src);
		if ($org_info) {
			if ($org_info[2] == 1) { 			if (function_exists("imagecreatefromgif")) {
					$img_org = imagecreatefromgif($src);
				}
			} elseif ($org_info[2] == 2) {
				if (function_exists("imagecreatefromjpeg")) {
					$img_org = imagecreatefromjpeg($src);
				}
			} elseif ($org_info[2] == 3) {
				if (function_exists("imagecreatefrompng")) {
					$img_org = imagecreatefrompng($src);
				}
			}
		} else {
			return error( '获取原始图像信息失败');
		}

			if ($width == '0' || $width > $org_info[0]) {
			$width = $org_info[0];
		}
		if ($height == '0' || $height > $org_info[1]) {
			$height = $org_info[1];
		}
			switch ($position) {
			case 0 :
			case 1 :
				$dst_x = 0;
				$dst_y = 0;
				break;
			case 2 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = 0;
				break;
			case 3 :
				$dst_x = $org_info[0] - $width;
				$dst_y = 0;
				break;
			case 4 :
				$dst_x = 0;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 5 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 6 :
				$dst_x = $org_info[0] - $width;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 7 :
				$dst_x = 0;
				$dst_y = $org_info[1] - $height;
				break;
			case 8 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = $org_info[1] - $height;
				break;
			case 9 :
				$dst_x = $org_info[0] - $width;
				$dst_y = $org_info[1] - $height;
				break;
			default:
				$dst_x = 0;
				$dst_y = 0;
		}
		if ($width == $org_info[0]) {
			$dst_x = 0;
		}
		if ($height == $org_info[1]) {
			$dst_y = 0;
		}

		if (function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$img_dst = imagecreatetruecolor($width, $height)) {
			imagecopyresampled($img_dst, $img_org, 0, 0, $dst_x, $dst_y, $width, $height, $width, $height);
		} else {
			return error( 'PHP环境不支持图片处理');
		}
		if (function_exists('imagejpeg')) {
			imagejpeg($img_dst, $desfile);
		} elseif (function_exists('imagepng')) {
			imagepng($img_dst, $desfile);
		}
		imagedestroy($img_dst);
		imagedestroy($img_org);
		return true;
	}
}